package com.ydlcalss.proviver.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.ydlcalss.proviver.domain.Goods;
import com.ydlcalss.proviver.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/goods")
//开启Hystrix  仪表盘
@EnableHystrixDashboard
@RestController
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Value("${server.port}")
    int port;

    @GetMapping("/findById/{id}")
        @HystrixCommand(fallbackMethod = "findById_fallback",commandProperties = {
            //设置Hystrix的超时时间，默认1s
                @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "3000"),
                //监控时间 默认5000 毫秒
                @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "5000"),
                //失败次数。默认20次
                @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "20"),
                //失败率 默认50%
                @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "50")
    })
    public Goods findById(@PathVariable("id") Integer id){
        Goods goods=goodsService.findById(id);


        if(id==1){
            //模拟出异常
            int a=1/0;
        }


        //模拟异常
//        int a=1/0;


        //模拟超时
        //模拟业务逻辑比较繁忙
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }


        goods.setTitle("端口号："+port);
        return goods;
    }
    /**
    定义一个降级方法
    1方法的返回值与原返回值一致
     2参数一致

     **/


    public Goods findById_fallback(Integer id){
        Goods goods=new Goods();
        goods.setGoodId(-1);
        goods.setTitle("provider提供方降级");
        goods.setPrice(-9.9);
        goods.setStock(-100);
        return goods;
    }

}
